package com.oyjd.ybx.front.service.impl;

import java.io.File;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.oyjd.ybx.bean.po.User;
import com.oyjd.ybx.bean.vo.UserVO;
import com.oyjd.ybx.business.user.dao.UserDao;
import com.oyjd.ybx.front.service.FrontSysService;
import com.oyjd.ybx.fw.util.CodeUtil;
import com.oyjd.ybx.fw.util.FileOP;
import com.oyjd.ybx.fw.util.HttpNet;
import com.oyjd.ybx.fw.util.MailUtil;
import com.oyjd.ybx.fw.util.SecurityUtil;

/**
 * 
 * 前端接口实现
 * 
 * @author <b>欧建东<br/>
 *         Email:oyjd@163.com</b>
 * @version 1.0
 */
@Transactional(readOnly = true)
public class FrontSysServiceImpl implements FrontSysService {

	private UserDao dao;

	@Autowired
	public void setDao(UserDao dao) {
		this.dao = dao;
	}

	private String adminMailHost;// 管理员邮件发送服务器
	private String adminMail;// 管理员邮箱
	private String adminMailPwd;// 管理员邮箱密码
	private String link;// 密码找回的链接地址
	private String emailTitle;// 密码找回的邮件标题
	private String emailContent;// 密码找回的邮件内容模版

	public void setAdminMailHost(String adminMailHost) {
		this.adminMailHost = adminMailHost;
	}

	public void setAdminMail(String adminMail) {
		this.adminMail = adminMail;
	}

	public void setAdminMailPwd(String adminMailPwd) {
		this.adminMailPwd = adminMailPwd;
	}

	public void setLink(String link) {
		this.link = link;
	}

	public void setEmailTitle(String emailTitle) {
		this.emailTitle = emailTitle;
	}

	public void setEmailContent(String emailContent) {
		this.emailContent = emailContent;
	}

	/**
	 * 发送密码找回邮件
	 * 
	 * @param vo
	 *            用户对象
	 * @param key
	 *            加密key
	 */
	public void sentMail(UserVO vo, String key) {
		String curTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		String c = MessageFormat.format(emailContent, vo.getName(), link + key, curTime);
		MailUtil.sendEmail(adminMailHost, adminMail, adminMailPwd, vo.getEmail(), emailTitle, c);
	}

	/**
	 * 填写宝宝资料
	 * 
	 * @param userId
	 * @param babySex
	 * @param babyBirthday
	 * @param babyName
	 * @param babyHeight
	 * @param babyWeight
	 * @throws Exception
	 */
	@Transactional(readOnly = false)
	public void updateBabyInfo(String userId, String picFileName, File pic, String babySex, String babyBirthday, String babyName, String babyHeight, String babyWeight) throws Exception {
		User u = (User) dao.queryById(User.class, userId);
		u.setBabySex(babySex);
		u.setBabyName(babyName);
		u.setBabyBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(babyBirthday));
		u.setBabyWeight(babyWeight);
		u.setBabyHeight(babyHeight);
		if (null != picFileName && !"".equals(picFileName)) {
			String picName = FileOP.getNewUUIDName(picFileName);
			FileOP.writeFile(CodeUtil.picPath + picName, pic);
			u.setBabyPic(picName);
		} else {
			u.setBabyPic(null);
		}
		dao.update(u);
	}

	private String qqUrl1 = "https://graph.qq.com/oauth2.0/me?access_token={0}";
	private String qqUrl2 = "https://graph.qq.com/user/get_user_info?oauth_consumer_key={0}&access_token={1}&openid={2}&format=json";

	/**
	 * 处理QQ登入回调
	 * 
	 * @param access_token
	 */
	@Transactional(readOnly = false)
	public UserVO qqLoginCallBack(String access_token) throws Exception {
		Date date = new Date();
		HttpNet hn = new HttpNet();
		byte[] b = hn.getBytesFromNet(MessageFormat.format(qqUrl1, access_token));
		String s = new String(b);
		String openId = s.substring(s.indexOf("openid") + 9, s.lastIndexOf("\""));
		//
		byte[] b2 = hn.getBytesFromNet(MessageFormat.format(qqUrl2, CodeUtil.qqAppId, access_token, openId));
		String s2 = new String(b2);
		JSONObject json = JSONObject.fromObject(s2);
		String nickname = json.getString("nickname");
		String sex = json.getString("gender").equals("男") ? "1" : "2";
		//
		User u = (User) dao.queryOneByHql("from " + User.class.getName() + " where account=?", new Object[] { openId });
		if (null != u) {
			u.setName(nickname);
			u.setSex(sex);
			u.setLastEditor("admin");
			u.setLastUpdateTime(date);
			dao.update(u);
		} else {
			u = new User();
			u.setRoleId("customer");
			u.setAccount(openId);
			u.setPwd(SecurityUtil.encoderByMd5(openId));
			u.setName(nickname);
			u.setSex(sex);
			u.setCreator("admin");
			u.setCreateTime(date);
			u.setLastEditor("admin");
			u.setLastUpdateTime(date);
			u.setStatus(0);
			dao.create(u);
		}
		//
		return (UserVO) dao.queryOneByHql("select new " + UserVO.class.getName() + UserVO.STRUCT + " from " + User.class.getName() + " user where userId=?", new Object[] { u.getUserId() });
	}

	private String baiduUrl = "https://openapi.baidu.com/rest/2.0/passport/users/getInfo?access_token={0}&format=json";

	/**
	 * 处理百度登入回调
	 * 
	 * @param access_token
	 */
	@Transactional(readOnly = false)
	public UserVO baiduLoginCallBack(String access_token) throws Exception {
		Date date = new Date();
		HttpNet hn = new HttpNet();
		hn.setEncoding("utf-8");
		byte[] b = hn.getBytesFromNet(MessageFormat.format(baiduUrl, access_token));
		String s = new String(b);
		s = decodeUnicode(s);
		JSONObject jobj = JSONObject.fromObject(s);
		String username = jobj.getString("username");
		String uid = jobj.getString("userid");
		//
		User u = (User) dao.queryOneByHql("from " + User.class.getName() + " where account=?", new Object[] { uid });
		if (null != u) {
			u.setName(username);
			u.setLastEditor("admin");
			u.setLastUpdateTime(date);
			dao.update(u);
		} else {
			u = new User();
			u.setRoleId("customer");
			u.setAccount(uid);
			u.setPwd(SecurityUtil.encoderByMd5(uid));
			u.setName(username);
			u.setSex("1");
			u.setCreator("admin");
			u.setCreateTime(date);
			u.setLastEditor("admin");
			u.setLastUpdateTime(date);
			u.setStatus(0);
			dao.create(u);
		}
		//
		return (UserVO) dao.queryOneByHql("select new " + UserVO.class.getName() + UserVO.STRUCT + " from " + User.class.getName() + " user where userId=?", new Object[] { u.getUserId() });

	}

	public static String decodeUnicode(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException("Malformed      encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't') {
						aChar = '\t';
					} else if (aChar == 'r') {
						aChar = '\r';
					} else if (aChar == 'n') {
						aChar = '\n';
					} else if (aChar == 'f') {
						aChar = '\f';
					}
					outBuffer.append(aChar);
				}
			} else {
				outBuffer.append(aChar);
			}
		}
		return outBuffer.toString();
	}

}
